import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javabean.connect;
import entity.person;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;


@WebServlet("/uploadServlet")
@MultipartConfig(location = "C:\\Users\\user\\Desktop\\third_comprehensive_experiment\\src\\main\\webapp\\images")
public class uploadServlet extends HttpServlet {
    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyJPADemoPU";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    private static EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> list = null;
        String head_img = null;
        try {
            list = upload.parseRequest(request);
            for (FileItem fi : list ) {
                //判断是否是文本域
                if(!fi.isFormField()){
                    if(fi.getSize()!=0){ //判断文件上传框是否选择了图片
                        head_img = fi.getName();
                        String path = getServletContext().getRealPath("/images");
                        InputStream is = fi.getInputStream();
                        FileOutputStream os = new FileOutputStream(new File(path, head_img));
                        IOUtils.copy(is,os);
                        os.close();
                        is.close();
                        fi.delete();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        try {
            doGet(request, response,head_img);
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response,String head_img) throws ServletException, IOException, SQLException {

        try {
            HttpSession session = request.getSession(true);
            String id = new String();
            Map <String, String> login2 = (Map <String, String>) request.getSession().getAttribute("login2");
            request.getSession().removeAttribute("login2");
            Connection conn = connect.getConnect("jpa/DSTest");
            id = login2.get("id");
            Statement stmt = conn.createStatement();
            String deleteSql = "delete from person where id=" + id;
            stmt.executeUpdate(deleteSql);

            EntityManager em = getEntityManager();
            EntityTransaction tx = em.getTransaction();


            person a = new person(login2.get("id"), login2.get("name"), login2.get("email"), login2.get("img"), login2.get("faculty_title"), login2.get("type"), login2.get("password"), login2.get("bname"), login2.get("bid"));
            if (a != null) {
                a.setImg(head_img);
                tx.begin();
                em.persist(a);
                tx.commit();
                Map <String, String> login3 = new HashMap <String, String>();

                login3.put("name", a.getName());
                login3.put("email", a.getEmail());
                login3.put("id", a.getId());
                login3.put("img", a.getImg());
                login3.put("type", a.getType());
                login3.put("faculty_title", a.getFaculty_title());
                login3.put("bname", a.getBname());
                login3.put("bid", a.getBid());
                login3.put("password", a.getPassword());

                session.setAttribute("login2", login3);

            } else {
                em.close();
                response.sendRedirect("/error.html");
            }
            em.close();

            response.sendRedirect("/user.jsp");
        }catch(IOException e ){
            response.sendRedirect("/error.html");
        }
    }
}
